package com.loveprogrammer.netty.simple;

import com.alibaba.fastjson2.JSON;
import com.loveprogrammer.command.client.ClientLoginTag;
import com.loveprogrammer.command.client.ClientTopic;
import com.loveprogrammer.command.server.ServerLoginOrRegisterTag;
import com.loveprogrammer.command.server.ServerTopic;
import com.loveprogrammer.dto.login.UserRegister;
import com.loveprogrammer.pojo.StringMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Scanner;

/**
 * @ClassName SocketClientHandler
 * @Description TODO
 * @Author admin
 * @Date 2024/1/29 17:41
 * @Version 1.0
 */
public class SocketClientHandler extends SimpleChannelInboundHandler<StringMessage> {

    private static final Logger logger = LoggerFactory.getLogger(SocketClientHandler.class);
    @Override
    public void exceptionCaught(ChannelHandlerContext arg0, Throwable arg1) {
        logger.info("异常发生", arg1);
    }

    @Override
    public void channelRead(ChannelHandlerContext arg0, Object msg) throws Exception {
        super.channelRead(arg0, msg);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext context, StringMessage data) {
        // logger.info("数据内容：data=" + data);

        // 注册一个用户
        System.out.println("请输入注册的用户名");
        Scanner input = new Scanner(System.in);
        String name = input.nextLine();
        UserRegister register = new UserRegister(ClientTopic.TOPIC_LOGIN, ClientLoginTag.TAG_LOGIN_REGISTER);
        register.setName(name);
        StringMessage msg = StringMessage.create(ServerTopic.TOPIC_LOGIN, ServerLoginOrRegisterTag.TAG_LOGIN_REGISTER);
        msg.setStatusCode(200);
        msg.setBody(JSON.toJSONString(register));
        context.channel().writeAndFlush(msg);
        logger.info("向服务器发送注册用户消息 {}",msg);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端连接建立");
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端连接断开");
        super.channelInactive(ctx);
    }

}
